package websocket.app.endpoints;

import javax.websocket.CloseReason;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import websocket.app.messaging.ListenersRegistry;
import websocket.app.messaging.TimerMessageListener;

@ServerEndpoint("/mem")
public class MemoryStatusEndpoint {
    private final static Log log = LogFactory.getLog(MemoryStatusEndpoint.class);
    
    @OnOpen
    public void onOpen(Session session) {
	log.info("Client initiated connection. Session id is " + session.getId());
	ListenersRegistry.getInstance().addListener(new TimerMessageListener(session.getId(), session.getAsyncRemote()));
    }
    
    @OnMessage
    public String onMessage(String message, Session session) {
	String serverMessage = "Handling message [" + message + "]";
	log.debug(serverMessage + " from client with session id " + session.getId());
	return serverMessage;
    }
    
    @OnClose
    public void onClose(CloseReason reason, Session session) {
	log.info("Client closed connection with session id " + session.getId());
	ListenersRegistry.getInstance().removeListener(session.getId());
    }
    
    @OnError
    public void onError(Throwable exception, Session session) {
	log.error("Error ocurred, session id is " + session.getId(), exception);
	ListenersRegistry.getInstance().removeListener(session.getId());
    }
}
